package com.base.redis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Component
public class RedisLock {

    @Resource
    private JedisClient jedisClient;

    //锁键
    private static final String LOCK_KEY = "REDIS_LOCK:";

    // 默认请求锁的超时时间(毫秒)
    private static final long TIMEOUT = 1000;

    // 默认锁的有效时间(s)
    public static final int EXPIRE = 500;

    /**
     * 获取分布式锁
     *
     * @return
     */
    public boolean tryLock(String key, String value) {
        long start = System.currentTimeMillis();
        while ((System.currentTimeMillis() - start) < TIMEOUT) {
            // setnx返回true, 则加锁成功
            if (jedisClient.setnx(LOCK_KEY + key, value)) {
                return true;
            }

            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return false;
    }

    /**
     * 解锁过程
     *
     * @return
     */
    public boolean unlock(String key, String value) {
        return jedisClient.delnx(LOCK_KEY + key, value);
    }
}
